<?php
if(Phpfox::getParam('countrydetector.enable_country_detector'))
{
    if(Phpfox::getParam('core.registration_enable_location'))
    {
        if(Phpfox::getParam('core.ip_infodb_api_key') != '')
        {
            $sUrl = 'http://api.ipinfodb.com/v2/ip_query.php?ip=' . Phpfox::getLib('request')->getIp() . '&key=' . Phpfox::getParam('core.ip_infodb_api_key');
            if (function_exists('file_get_contents') && ini_get('allow_url_fopen'))
            {
                $sXML = file_get_contents($sUrl);
            }
            else
            {
                $sXML = Phpfox::getLib('request')->send($sUrl, array(), 'GET');
            }
            $aCallback = Phpfox::getLib('xml.parser')->parse($sXML, 'UTF-8');
            
            $aCountries = Phpfox::getService('core.country')->get();

            if (!empty($aCallback['CountryCode']))
            {
                foreach($aCountries as $sCode => $sCountry)
                {
                    if(strtolower($aCallback['CountryCode']) == strtolower($sCode))
                    {

?> 
                       
<script type="text/javascript">
    /* update the country */
    $('#country_iso option[value=<?php echo $sCode; ?>]').attr('selected', 'selected');
        
    /* get the states/provinces of the country */
    $.ajaxCall('core.getChildren', 'country_iso=<?php echo $sCode; ?>', 'GET');
    
    /* Wait for the regions to be available */
    var repeat = window.setInterval("loadRegions()", 500);
    /* If after 5 attempts there are no regions, then stop*/
    var count = 1;

    function loadRegions()
    {
        if($('#js_country_child_id_value option').length > 1)
        {
            $('#js_country_child_id_value option').each(function(sValue){
                if($('#js_country_child_id_value option[value='+$(this).attr('value')+']').text().toLowerCase() == "<?php echo $aCallback['RegionName']; ?>".toLowerCase())
                {
                    $('#js_country_child_id_value option[value='+$(this).attr('value')+']').attr('selected', 'selected');
                    window.clearInterval(repeat);
                }
            });
        }
        if(count > 10)
        {
            window.clearInterval(repeat);
        }
        count++;
    }
</script>

<?

                    }
                }
            }
        }
    }
}
?>